import targetUtils from './target-utils.js'
/**
 * Model contains zero or more multi-layer datasets
 * 私有方法待解决
 */
export default class Model {
  constructor() {
    this.datasets = []
    this.defaultTargets = []
  }

  forEachLayer(cb) {
    let i = 0
    this.datasets.forEach((dataset) => {
      dataset.layers.forEach((lyr) => {
        cb(lyr, dataset, i += 1)
      })
    })
  }
  addDataset(dataset) {
    this.setDefaultTarget(dataset.layers, dataset)
    return this
  }
  getDatasets() {
    return this.datasets
  }
  getLayers() {
    const layers = []
    this.forEachLayer((lyr, dataset) => {
      layers.push(this.layerObject(lyr, dataset))
    })
    return layers
  }
  isEmpty() {
    return this.datasets.length === 0
  }
  getDefaultTargets() {
    if (defaultTargets.length === 0 && !this.isEmpty()) {
      this.defaultTargets = [{dataset: this.datasets[0], layers: this.datasets[0].layers.slice(0, 1)}]
    }
    return this.defaultTargets
  }
  setDefaultTarget(layers, dataset) {
    if (this.datasets.indexOf(dataset) === -1) {
      this.datasets.push(dataset)
    }
    this.defaultTargets = [{
      layers: layers.concat(),
      dataset: dataset
    }]
  }
  layerObject(lyr, dataset) {
    return {
      layer: lyr,
      dataset: dataset
    }
  }
  findCommandTargets(pattern, type) {
    if (pattern) {
      return targetUtils.findCommandTargets(this, pattern, type)
    }
    return this.getDefaultTargets() || []
  }
}
